import warnings
from selenium.webdriver.common import utils
from selenium.webdriver.ie.service import Service as IEService
from selenium.webdriver.ie.options import Options as IEOptions

from ..remote.webdriver import WebDriver as HSWebDriver


class WebDriver(HSWebDriver):
    """ Controls the IEServerDriver and allows you to drive Internet Explorer """

    def __init__(self, executable_path='IEDriverServer.exe', capabilities=None,
                 port=0, timeout=30, host=None, log_level=None, log_file=None, options=None,
                 ie_options=None, desired_capabilities=None):
        if ie_options:
            warnings.warn('use options instead of ie_options', DeprecationWarning)
            options = ie_options
        self.port = port
        if self.port == 0:
            self.port = utils.free_port()
        self.host = host
        self.log_level = log_level
        self.log_file = log_file

        if capabilities is None and desired_capabilities:
            capabilities = desired_capabilities

        if options is None:
            if capabilities is None:
                capabilities = self.create_options().to_capabilities()
        else:
            if capabilities is None:
                capabilities = options.to_capabilities()
            else:
                # desired_capabilities stays as passed in
                capabilities.update(options.to_capabilities())

        self.iedriver = IEService(
            executable_path,
            port=self.port,
            host=self.host,
            log_level=self.log_level,
            log_file=self.log_file)

        self.iedriver.start()

        HSWebDriver.__init__(
            self,
            command_executor='http://localhost:%d' % self.port,
            desired_capabilities=capabilities)
        self._is_remote = False

    def quit(self):
        HSWebDriver.quit(self)
        self.iedriver.stop()

    def create_options(self):
        return IEOptions()
